<template>
  <div class="product-detail-container">
    <div class="header-section">
      <el-page-header @back="goBack" :title="'返回'" :content="'商品详情'" />
    </div>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>

    <template v-else>
      <!-- 商品基本信息 -->
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
            <el-tag :type="productInfo.status === 1 ? 'success' : 'info'">
              {{ productInfo.status === 1 ? "上架中" : "已下架" }}
            </el-tag>
          </div>
        </template>
        <div class="product-info">
          <div class="product-header">
            <div class="product-image">
              <el-image
                :src="productInfo.mainImage"
                fit="cover"
                :preview-src-list="[productInfo.mainImage]"
                style="width: 120px; height: 120px; border-radius: 5px"
              ></el-image>
            </div>
            <div class="product-meta">
              <h2 class="product-name">{{ productInfo.name }}</h2>
              <div class="info-item">
                <span class="label">品牌：</span>
                <span class="value">{{
                  productInfo.brand || "无品牌"
                }}</span>
              </div>
              <div class="info-item">
                <span class="label">分类：</span>
                <span class="value">{{
                  productInfo.categoryName || "未分类"
                }}</span>
              </div>
              <div class="info-item">
                <span class="label">创建时间：</span>
                <span class="value">{{ productInfo.createdAt }}</span>
              </div>
              <div class="info-item">
                <span class="label">更新时间：</span>
                <span class="value">{{ productInfo.updatedAt }}</span>
              </div>
            </div>
          </div>

          <div class="product-description">
            <h3>商品描述</h3>
            <p>{{ productInfo.description || "暂无商品描述" }}</p>
          </div>
        </div>
      </el-card>

      <!-- 商品图片 -->
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>商品图片</span>
          </div>
        </template>
        <div class="product-images">
          <el-empty
            v-if="!productImages.length"
            description="暂无商品图片"
          ></el-empty>
          <div v-else class="image-gallery">
            <el-image
              v-for="(image, index) in productImages"
              :key="index"
              :src="image"
              :preview-src-list="productImages"
              style="
                width: 120px;
                height: 120px;
                margin: 5px;
                border-radius: 5px;
              "
            ></el-image>
          </div>
        </div>
      </el-card>

      <!-- SKU信息 -->
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>商品规格</span>
          </div>
        </template>
        <div class="sku-info">
          <div v-if="skuList.length === 0" class="no-data">暂无商品规格信息</div>
          <el-table v-else :data="skuList" border style="width: 100%">
            <el-table-column label="规格图片" width="120">
              <template #default="scope">
                <el-image
                  :src="
                    getSkuImage(scope.row)
                  "
                  style="width: 50px; height: 50px"
                  fit="cover"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column label="规格名称" prop="title" width="180" />
            <el-table-column label="规格值" width="180">
              <template #default="scope">
                <div>
                  {{ formatSpecs(scope.row.specs) }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="销售价" width="120">
              <template #default="scope">
                <span class="price">¥{{ formatPrice(scope.row.price) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="原价" width="120">
              <template #default="scope">
                <span class="original-price"
                  >¥{{ formatPrice(scope.row.originalPrice) }}</span
                >
              </template>
            </el-table-column>
            <el-table-column label="成本价" width="120">
              <template #default="scope">
                <span>¥{{ formatPrice(scope.row.costPrice) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="库存" prop="stock" width="100" />
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.saleable ? 'success' : 'info'">
                  {{ scope.row.saleable ? "上架中" : "已下架" }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>

      <!-- 销售信息 -->
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>销售信息</span>
          </div>
        </template>
        <div class="sales-info">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="8">
              <div class="stats-card">
                <div class="stats-icon" style="background-color: #67c23a">
                  <el-icon :size="24"><ShoppingCart /></el-icon>
                </div>
                <div class="stats-content">
                  <div class="stats-value">{{ salesData.totalSales || 0 }}</div>
                  <div class="stats-label">总销量</div>
                </div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="8">
              <div class="stats-card">
                <div class="stats-icon" style="background-color: #409eff">
                  <el-icon :size="24"><Money /></el-icon>
                </div>
                <div class="stats-content">
                  <div class="stats-value">
                    ¥{{ formatPrice(salesData.totalRevenue) }}
                  </div>
                  <div class="stats-label">总收入</div>
                </div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="8">
              <div class="stats-card">
                <div class="stats-icon" style="background-color: #e6a23c">
                  <el-icon :size="24"><Star /></el-icon>
                </div>
                <div class="stats-content">
                  <div class="stats-value">{{ salesData.ratings || 0 }}</div>
                  <div class="stats-label">评价数</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="handleEdit">编辑商品</el-button>
        <el-button type="danger" @click="handleChangeStatus">{{
          productInfo.status === 1 ? "下架商品" : "上架商品"
        }}</el-button>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { ShoppingCart, Money, Star } from "@element-plus/icons-vue";
import { getProductDetail, updateProductStatus } from "@/api/products";
import { getSkuByProduct } from "@/api/productSku";
import request from "@/utils/request";

const route = useRoute();
const router = useRouter();

const productId = computed(() => route.params.id);
const loading = ref(true);
const productInfo = ref({});
const productImages = ref([]);
const skuList = ref([]);
const salesData = ref({
  totalSales: 0,
  totalRevenue: 0,
  ratings: 0,
});

// 格式化价格
const formatPrice = (price) => {
  if (price === undefined || price === null) return "0.00";
  return parseFloat(price).toFixed(2);
};

// 格式化规格
const formatSpecs = (specs) => {
  if (!specs) return "";
  try {
    const specsObj = typeof specs === "string" ? JSON.parse(specs) : specs;
    return Object.entries(specsObj)
      .map(([key, value]) => `${key}: ${value}`)
      .join(", ");
  } catch (e) {
    return specs;
  }
};

// 返回上一页
const goBack = () => {
  // 检查是否从首页来的
  if (route.query.source === "dashboard") {
    // 使用location.href进行直接导航，确保页面刷新
    window.location.href = "/home/index";
  } else {
    window.location.href = "/home/products";
  }
};

// 获取商品销售数据
const fetchProductSalesData = async (productId) => {
  try {
    const res = await request.get(`/admin/products/${productId}/sales-data`);
    if (res.code === 200) {
      return res.data;
    }
    return {
      totalSales: 0,
      totalRevenue: 0,
      ratings: 0,
    };
  } catch (error) {
    console.error("获取商品销售数据失败:", error);
    return {
      totalSales: 0,
      totalRevenue: 0,
      ratings: 0,
    };
  }
};

// 获取商品详情
const fetchProductDetail = async () => {
  loading.value = true;
  try {
    // 获取商品基本信息
    const res = await getProductDetail(productId.value);
    console.log("商品详情数据:", res.data);
    
    if (res.code === 200) {
      productInfo.value = res.data;
      
      // 处理商品图片
      if (res.data.images) {
        try {
          const images = JSON.parse(res.data.images);
          productImages.value = Array.isArray(images) ? images : [];
          if (
            res.data.mainImage &&
            !productImages.value.includes(res.data.mainImage)
          ) {
            productImages.value.unshift(res.data.mainImage);
          }
        } catch (e) {
          productImages.value = res.data.mainImage ? [res.data.mainImage] : [];
        }
      } else {
        productImages.value = res.data.mainImage ? [res.data.mainImage] : [];
      }
      
      // 获取SKU列表
      const skuRes = await getSkuByProduct(productId.value);
      console.log("SKU列表数据:", skuRes.data);
      
      if (skuRes.code === 200) {
        // 确保SKU规格数据正确处理
        skuList.value = skuRes.data || [];
        
        // 遍历处理每个SKU的规格数据，确保格式正确
        skuList.value.forEach(sku => {
          if (sku.specs && typeof sku.specs === 'string') {
            try {
              // 尝试解析规格JSON字符串
              const specsObj = JSON.parse(sku.specs);
              // 将解析后的对象直接赋值给specs属性
              sku.specsObj = specsObj;
            } catch (e) {
              console.error("解析SKU规格失败:", e);
              sku.specsObj = {};
            }
          } else {
            sku.specsObj = {};
          }
        });
      }
      
      // 获取销售数据
      try {
        salesData.value = await fetchProductSalesData(productId.value);
      } catch (error) {
        console.error("获取销售数据失败, 使用默认值:", error);
      }
    } else {
      ElMessage.error(res.msg || "获取商品详情失败");
    }
  } catch (error) {
    console.error("获取商品详情失败:", error);
    ElMessage.error("获取商品详情失败");
  } finally {
    loading.value = false;
  }
};

// 编辑商品
const handleEdit = () => {
  router.push(`/home/products/edit/${productId.value}`);
};

// 修改商品状态（上架/下架）
const handleChangeStatus = async () => {
  const action = productInfo.value.status === 1 ? "下架" : "上架";
  const newStatus = productInfo.value.status === 1 ? 0 : 1;

  ElMessageBox.confirm(`确定要${action}该商品吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await updateProductStatus(productId.value, newStatus);

        if (res.code === 200) {
          productInfo.value.status = newStatus;
          ElMessage.success(`商品${action}成功`);
        } else {
          ElMessage.error(res.msg || `商品${action}失败`);
        }
      } catch (error) {
        console.error(`商品${action}失败:`, error);
        ElMessage.error(`商品${action}失败`);
      }
    })
    .catch(() => {});
};

// 获取SKU图片
const getSkuImage = (sku) => {
  try {
    if (sku.images) {
      const imagesArray = JSON.parse(sku.images);
      if (Array.isArray(imagesArray) && imagesArray.length > 0) {
        return imagesArray[0];
      }
    }
  } catch (e) {
    console.error("解析SKU图片失败:", e);
  }
  return productInfo.value.mainImage || '';
};

onMounted(() => {
  fetchProductDetail();
});
</script>

<style scoped>
.product-detail-container {
  padding: 20px;
}

.header-section {
  margin-bottom: 20px;
}

.loading-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-item {
  margin-bottom: 10px;
  display: flex;
}

.label {
  width: 100px;
  color: #606266;
}

.value {
  flex: 1;
  color: #303133;
}

.product-header {
  display: flex;
  margin-bottom: 20px;
}

.product-image {
  margin-right: 20px;
}

.product-meta {
  flex: 1;
}

.product-name {
  margin-top: 0;
  margin-bottom: 15px;
  color: #303133;
}

.product-description {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.product-description h3 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #303133;
}

.product-description p {
  color: #606266;
  line-height: 1.6;
}

.image-gallery {
  display: flex;
  flex-wrap: wrap;
}

.price {
  color: #f56c6c;
  font-weight: 500;
}

.original-price {
  color: #909399;
  text-decoration: line-through;
}

.stats-card {
  display: flex;
  align-items: center;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.stats-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 50px;
  height: 50px;
  border-radius: 8px;
  margin-right: 15px;
  color: white;
}

.stats-content {
  flex: 1;
}

.stats-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.stats-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.no-data {
  padding: 40px 0;
  text-align: center;
  color: #909399;
  font-size: 14px;
}
</style> 